<?php
include 'includes/db.php';
// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接是否成功
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// 获取表单数据
$username = $_POST['username'];
$password = $_POST['password'];

// 检查用户名是否已存在
$stmt = $conn->prepare("SELECT id FROM users WHERE username = ?");
if (!$stmt) {
    die("准备语句失败: " . $conn->error);
}
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    echo json_encode(['success' => false, 'message' => '用户名已存在']);
    exit;
}

// 哈希密码
$password = md5($password);

// 插入新用户
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
if (!$stmt) {
    die("准备语句失败: " . $conn->error);
}
$stmt->bind_param("ss", $username, $password);

if ($stmt->execute()) {
    echo json_encode(['success' => true, 'message' => '注册成功']);
} else {
    echo json_encode(['success' => false, 'message' => '注册失败，请稍后再试']);
}

// 关闭连接
$conn->close();
?>